package com.hdumooc.utils;

import org.apache.commons.dbcp.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @description: DBCP 工具类
 * @author: Jieyao Lu
 * @date: 2023/11/18 15:48
**/
public class DBCPUtils {

    // 1.定义常量 保存数据库连接的相关信息
    public static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/cp_lessons?characterEncoding=UTF-8";
    public static final String USER = "root";
    public static final String PASSWORD = "root";

    // 2.创建连接池对象（由 DBCP 提供的实现类）
    public static BasicDataSource dataSource = new BasicDataSource();

    // 3.使用静态代码块进行设置
    static {
        dataSource.setDriverClassName(DRIVER);
        dataSource.setUrl(URL);
        dataSource.setUsername(USER);
        dataSource.setPassword(PASSWORD);
    }

    // 4.获取连接的方法
    public static Connection getConnection() throws SQLException {
        // 从连接池中获取连接
        return dataSource.getConnection();
    }

    // 5.释放资源的方法
    public static void close(Connection connection, Statement statement) {
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
